<template>
  <div class="my-posts">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header>
        <el-menu mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" router>
          <div class="logo">
            <i class="el-icon-reading"></i>
            校园二手书交易平台
          </div>
          <el-menu-item index="/home">首页</el-menu-item>
          <el-menu-item index="/market">书籍市场</el-menu-item>
          <el-menu-item index="/my-posts">我的发布</el-menu-item>
          <el-menu-item index="/messages">消息中心</el-menu-item>
        </el-menu>
      </el-header>

      <el-main>
        <div class="content-box">
          <div class="header-section">
            <h2 class="page-title">我的发布</h2>
            <el-button type="primary" @click="showPublishDialog" class="publish-btn" icon="el-icon-plus">
              发布新书籍
            </el-button>
          </div>

          <el-tabs v-model="activeTab" class="custom-tabs">
            <el-tab-pane label="在售书籍" name="selling">
              <el-table 
                :data="sellingBooks" 
                v-loading="loading"
                stripe
                border
                class="custom-table"
              >
                <el-table-column prop="title" label="书名" min-width="180"></el-table-column>
                <el-table-column prop="author" label="作者" width="120"></el-table-column>
                <el-table-column prop="price" label="价格" width="100">
                  <template slot-scope="scope">
                    <span class="price-text">¥{{ scope.row.price }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="bookCondition" label="成色" width="100">
                  <template slot-scope="scope">
                    <el-tag :type="getConditionType(scope.row.bookCondition)" size="small">
                      {{ scope.row.bookCondition }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="发布时间" width="180"></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template slot-scope="scope">
                    <el-tag type="success" size="small">{{ scope.row.status }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                  <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">下架</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  background
                  @current-change="handlePageChange"
                  :current-page="currentPage"
                  :page-size="pageSize"
                  :total="total"
                  layout="total, prev, pager, next, jumper"
                >
                </el-pagination>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>

    <!-- 发布/编辑书籍对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="50%"
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <el-form :model="bookForm" :rules="rules" ref="bookForm" label-width="80px" class="book-form">
        <el-form-item label="书籍图片" prop="imageUrl" class="image-upload-item">
          <el-upload
            class="book-image-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="uploadImage"
          >
            <img v-if="bookForm.imageUrl" :src="bookForm.imageUrl" class="book-image">
            <i v-else class="el-icon-plus book-image-uploader-icon"></i>
          </el-upload>
          <div class="image-tip">支持jpg、png格式，大小不超过2MB</div>
        </el-form-item>
        <el-form-item label="书名" prop="title">
          <el-input v-model="bookForm.title" placeholder="请输入书名"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="bookForm.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="成色" prop="bookCondition">
          <el-select v-model="bookForm.bookCondition" placeholder="请选择成色">
            <el-option label="全新" value="全新"></el-option>
            <el-option label="9成新" value="9成新"></el-option>
            <el-option label="8成新" value="8成新"></el-option>
            <el-option label="7成新" value="7成新"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="bookForm.description" 
            rows="4"
            placeholder="请输入书籍描述信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'MyPostsPage',
  data() {
    return {
      activeTab: 'selling',
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 30,
      dialogVisible: false,
      dialogTitle: '发布新书籍',
      sellingBooks: [],
      bookForm: {
        title: '',
        author: '',
        price: 0,
        bookCondition: '',
        description: '',
        imageUrl: ''
      },
      rules: {
        title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
        author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        bookCondition: [{ required: true, message: '请选择成色', trigger: 'change' }]
      }
    }
  },
  methods: {
    getConditionType(bookCondition) {
      const types = {
        '全新': 'success',
        '9成新': 'success',
        '8成新': 'warning',
        '7成新': 'info'
      }
      return types[bookCondition] || 'info'
    },

    async getBookList() {
      try {
        this.loading = true
        const res = await request.get("/api/myposts/list", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize
          }
        })
        if(res.data.code === 1){
          this.sellingBooks = res.data.data.list
          this.total = res.data.data.total
        }else{
          this.$message({
            type: 'error',
            message: res.data.msg || '获取我的发布失败'
          })
        }
      } catch (error) {
        this.$message.error('获取我的发布失败')
      } finally {
        this.loading = false
      }
    },

    showPublishDialog() {
      this.dialogTitle = '发布新书籍'
      this.bookForm = {
        title: '',
        author: '',
        price: 0,
        bookCondition: '',
        description: '',
        imageUrl: ''
      }
      this.dialogVisible = true
    },

    handleEdit(book) {
      this.dialogTitle = '编辑书籍'
      // 添加 id 字段，确保识别为编辑操作
      this.bookForm = {
        id: book.id, // 添加 id 字段
        imageUrl: book.imageUrl || '',
        title: book.title || '',
        author: book.author || '',
        price: book.price || 0,
        bookCondition: book.bookCondition || '',
        description: book.description || ''
      }
      this.dialogVisible = true
    },

    async handleDelete(id) {
      try {
        await this.$confirm('确认下架该书籍吗？', '提示', {
          type: 'warning'
        })
        const res = await request.delete(`/api/myposts/book/${id}`)
        if (res.data.code === 1) {
          this.$message.success('下架成功')
          this.getBookList()
        } else {
          this.$message.error(res.data.msg || '下架失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('下架失败')
        }
      }
    },

    handlePageChange(page) {
      this.currentPage = page
      this.getBookList()
    },
    
    async handleSubmit() {
      try {
        await this.$refs.bookForm.validate()
        let res
        if (this.bookForm.id) {
          res = await request.put(`/api/myposts/book/update`, this.bookForm)
          if (res.data.code === 1) {
            this.$message.success('编辑成功')
            this.dialogVisible = false
            this.getBookList()
          } else {
            this.$message.error(res.data.msg || '编辑失败')
          }
        } else {
          res = await request.post('/api/myposts/book/save', this.bookForm)
          if (res.data.code === 1) {
            this.$message.success('发布成功')
            this.dialogVisible = false
            this.getBookList()
          } else {
            this.$message.error(res.data.msg || '发布失败')
          }
        }
      } catch (error) {
        this.$message.error(this.bookForm.id ? '编辑失败' : '发布失败')
      }
    },

    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },

    async uploadImage(options) {
      try {
        const formData = new FormData();
        formData.append('file', options.file);
        
        const res = await request.post('/api/upload/avatar', formData);
        if (res.data.code === 1) {
          this.bookForm.imageUrl = res.data.data;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error(res.data.msg || '图片上传失败');
        }
      } catch (error) {
        this.$message.error('图片上传失败');
      }
    }
  },
  created() {
    this.getBookList()
  }
}
</script>

<style scoped>
.logo {
  float: left;
  line-height: 60px;
  margin: 0 20px;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.logo i {
  margin-right: 10px;
  font-size: 24px;
}

.my-posts {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

.el-main {
  padding: 20px;
}

.content-box {
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.publish-btn {
  padding: 12px 20px;
}

.custom-tabs {
  margin-top: 20px;
}

.custom-table {
  margin-top: 20px;
}

.price-text {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  text-align: center;
  margin-top: 20px;
  padding: 10px 0;
}

.custom-dialog .el-dialog__body {
  padding: 20px 40px;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}

.book-form {
  max-width: 600px;
  margin: 0 auto;
}

.book-form .el-form-item {
  margin-bottom: 22px;
}

.book-form .el-input,
.book-form .el-input-number,
.book-form .el-select {
  width: 100%;
}

.book-form .el-textarea__inner {
  min-height: 120px;
}

.image-upload-item {
  text-align: center;
  margin-bottom: 30px;
}

.book-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  transition: all 0.3s;
  margin: 0 auto;
}

.book-image-uploader:hover {
  border-color: #409EFF;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.book-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.book-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.image-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.el-input-number {
  width: 180px;
}

.el-table .el-button--mini {
  padding: 6px 12px;
}

.el-tag {
  font-weight: 500;
}
</style>